/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AgendaUI.java
 *
 * Created on 15-abr-2009, 12:10:12
 */
package agenda;

import es.random.agenda.datos.*;
import es.random.java.librerias.gestion.Gestor;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;

/**
 *
 * @author AdminLocal
 */
public class AgendaUI extends javax.swing.JFrame
{

    /** Creates new form AgendaUI */
    public AgendaUI()
    {
        initComponents();


        TableModel modelo = new ContactoTableModel();

        // Cargamos los datos de nuestra tabla
        tablaDatos.setModel(modelo);
        // La enlazamos para que cuando se seleccione un registro, se carguen los datos en la ficha
        ListSelectionModel modeloSeleccion = tablaDatos.getSelectionModel();
        // Solo permitimos seleccionar uno cada vez
        modeloSeleccion.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        modeloSeleccion.addListSelectionListener(new ListSelectionListener()
        {

            public void valueChanged(ListSelectionEvent e)
            {
                actualizarDetalle(tablaDatos.getSelectedRow());
            }
        });
        validate();



    // Otra Forma sencilla de generar una tabla a partir de nuestros datos
        /*
    JTable jTable1 = new JTable(gestor.obtenerMatriz(), gestor.obtenerNombresColumnas());
    jScrollPane1 = new JScrollPane(jTable1);
    jSplitPane1.setBottomComponent(jScrollPane1);

    validate();
     */
    }

    private void actualizarDetalle(int selectedRow)
    {
        for (int i = 0; i < tablaDatos.getModel().getColumnCount(); i++) {
            switch (i) {
                case 0:
                    textoNombre.setText((String) tablaDatos.getModel().getValueAt(selectedRow, i));
                    break;
                case 1:
                    textoPrimerApellido.setText((String) tablaDatos.getModel().getValueAt(selectedRow, i));
                    break;
                case 2:
                    textoSegundoApellido.setText((String) tablaDatos.getModel().getValueAt(selectedRow, i));
                    break;
                case 3:
                    textoTelefono.setText((String) tablaDatos.getModel().getValueAt(selectedRow, i));
                    break;
                case 4:
                    textoMovil.setText((String) tablaDatos.getModel().getValueAt(selectedRow, i));
                    break;
                case 5:
                    textoEmail.setText((String) tablaDatos.getModel().getValueAt(selectedRow, i));
                    break;
                case 6:
                    textoDireccion.setText((String) tablaDatos.getModel().getValueAt(selectedRow, i));
                    break;
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PopUpTabla = new javax.swing.JPopupMenu();
        opcionNuevoContacto = new javax.swing.JMenuItem();
        opcionBorrarContacto = new javax.swing.JMenuItem();
        jSplitPane1 = new javax.swing.JSplitPane();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        PanelFicha = new javax.swing.JPanel();
        textoNombre = new javax.swing.JTextField();
        textoPrimerApellido = new javax.swing.JTextField();
        textoSegundoApellido = new javax.swing.JTextField();
        textoTelefono = new javax.swing.JTextField();
        textoMovil = new javax.swing.JTextField();
        textoEmail = new javax.swing.JTextField();
        textoDireccion = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaDatos = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        opcionCargar = new javax.swing.JMenuItem();
        opcionGuardar = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        opcionNuevoContacto.setText("Nuevo Contacto");
        opcionNuevoContacto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcionNuevoContactoActionPerformed(evt);
            }
        });
        PopUpTabla.add(opcionNuevoContacto);

        opcionBorrarContacto.setText("Borrar Contacto");
        opcionBorrarContacto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcionBorrarContactoActionPerformed(evt);
            }
        });
        PopUpTabla.add(opcionBorrarContacto);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jSplitPane1.setDividerLocation(175);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        textoNombre.setName("0"); // NOI18N
        textoNombre.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoTextoCambiado(evt);
            }
        });

        textoPrimerApellido.setName("1"); // NOI18N
        textoPrimerApellido.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoTextoCambiado(evt);
            }
        });

        textoSegundoApellido.setName("2"); // NOI18N
        textoSegundoApellido.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoTextoCambiado(evt);
            }
        });

        textoTelefono.setName("3"); // NOI18N
        textoTelefono.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoTextoCambiado(evt);
            }
        });

        textoMovil.setName("4"); // NOI18N
        textoMovil.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoTextoCambiado(evt);
            }
        });

        textoEmail.setName("5"); // NOI18N
        textoEmail.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoTextoCambiado(evt);
            }
        });

        textoDireccion.setName("6"); // NOI18N
        textoDireccion.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoTextoCambiado(evt);
            }
        });

        jLabel1.setText("Nombre:");

        jLabel2.setText("Primer Apellido:");

        jLabel3.setText("Segundo Apellido:");

        jLabel4.setText("Teléfono Fijo:");

        jLabel5.setText("Teléfono Móvil:");

        jLabel6.setText("E-Mail:");

        jLabel7.setText("Dirección:");

        javax.swing.GroupLayout PanelFichaLayout = new javax.swing.GroupLayout(PanelFicha);
        PanelFicha.setLayout(PanelFichaLayout);
        PanelFichaLayout.setHorizontalGroup(
            PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelFichaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PanelFichaLayout.createSequentialGroup()
                        .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textoNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4)
                            .addComponent(textoTelefono))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(PanelFichaLayout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, PanelFichaLayout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addGap(75, 75, 75))
                                .addGroup(PanelFichaLayout.createSequentialGroup()
                                    .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(textoMovil, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                                        .addComponent(textoPrimerApellido, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))))
                        .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel6)
                            .addComponent(textoEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                            .addComponent(textoSegundoApellido, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)))
                    .addGroup(PanelFichaLayout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textoDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)))
                .addContainerGap())
        );
        PanelFichaLayout.setVerticalGroup(
            PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelFichaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textoSegundoApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textoPrimerApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textoTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textoEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textoMovil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(PanelFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textoDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Contactos", PanelFicha);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 483, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 146, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("tab2", jPanel2);

        jSplitPane1.setTopComponent(jTabbedPane1);

        tablaDatos.setModel(setTableModelAgenda());
        tablaDatos.setComponentPopupMenu(PopUpTabla);
        tablaDatos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tablaMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tablaDatos);

        jSplitPane1.setBottomComponent(jScrollPane1);

        jMenu1.setLabel("Archivo");

        opcionCargar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        opcionCargar.setLabel("Cargar Agenda");
        opcionCargar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcionCargar(evt);
            }
        });
        jMenu1.add(opcionCargar);

        opcionGuardar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
        opcionGuardar.setLabel("Guardar Agenda");
        opcionGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcionGuardar(evt);
            }
        });
        jMenu1.add(opcionGuardar);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowActivated
    {//GEN-HEADEREND:event_formWindowActivated
        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowActivated

    private void formMousePressed(java.awt.event.MouseEvent evt)//GEN-FIRST:event_formMousePressed
    {//GEN-HEADEREND:event_formMousePressed
        // TODO add your handling code here:
    }//GEN-LAST:event_formMousePressed

    private void campoTextoCambiado(java.awt.event.FocusEvent evt)//GEN-FIRST:event_campoTextoCambiado
    {//GEN-HEADEREND:event_campoTextoCambiado

        String contenido = ((JTextField) evt.getSource()).getText();

        int campo = Integer.parseInt(((JTextField) evt.getSource()).getName());
        int registro = tablaDatos.getSelectedRow();
        if (!(contenido.equals((String) tablaDatos.getModel().getValueAt(registro, campo)))) {
            tablaDatos.getModel().setValueAt(contenido, registro, campo);
            tablaDatos.repaint();
        }

}//GEN-LAST:event_campoTextoCambiado

    private void opcionNuevoContactoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_opcionNuevoContactoActionPerformed
    {//GEN-HEADEREND:event_opcionNuevoContactoActionPerformed

        ContactoTableModel modelo = (ContactoTableModel) tablaDatos.getModel();
        modelo.añadirFila();


        tablaDatos.addRowSelectionInterval(modelo.getRowCount()-1, modelo.getRowCount()-1);
        tablaDatos.repaint();
        // Pasamos el foco al primer campo para que el usuario lo edite
        textoNombre.requestFocusInWindow();

}//GEN-LAST:event_opcionNuevoContactoActionPerformed

    private void opcionBorrarContactoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_opcionBorrarContactoActionPerformed
    {//GEN-HEADEREND:event_opcionBorrarContactoActionPerformed
        int fila = tablaDatos.getSelectedRow();
        if(fila > -1) {
            ContactoTableModel modelo = (ContactoTableModel) tablaDatos.getModel();
            modelo.borrarFila(fila);
            tablaDatos.repaint();
            // Para no despistar al usuario, seleccionamos la fila anterior y así se cargan estos datos en el formulario
            int filaNueva= ( fila > 0 ) ? fila-1 : 0;
            tablaDatos.setRowSelectionInterval(filaNueva, filaNueva);
        }

    }//GEN-LAST:event_opcionBorrarContactoActionPerformed

    private void tablaMouseReleased(java.awt.event.MouseEvent evt)//GEN-FIRST:event_tablaMouseReleased
    {//GEN-HEADEREND:event_tablaMouseReleased
        int fila = tablaDatos.rowAtPoint(evt.getPoint());
        int columna = tablaDatos.columnAtPoint(evt.getPoint());

        if(fila > -1) {
            tablaDatos.setRowSelectionInterval(fila, fila);

            switch(columna) {
                case 0:
                    textoNombre.requestFocusInWindow();
                    break;
                case 1:
                    textoPrimerApellido.requestFocusInWindow();
                    break;
                case 2:
                    textoSegundoApellido.requestFocusInWindow();
                    break;
                case 3:
                    textoTelefono.requestFocusInWindow();
                    break;
                case 4:
                    textoMovil.requestFocusInWindow();
                    break;
                case 5:
                    textoEmail.requestFocusInWindow();
                    break;
                case 6:
                    textoDireccion.requestFocusInWindow();
                    break;
            }
        }
}//GEN-LAST:event_tablaMouseReleased

    private void opcionCargar(java.awt.event.ActionEvent evt)//GEN-FIRST:event_opcionCargar
    {//GEN-HEADEREND:event_opcionCargar
        ContactoTableModel modelo = ((ContactoTableModel)tablaDatos.getModel());
        modelo.cargarAgenda();
        tablaDatos.repaint();
    }//GEN-LAST:event_opcionCargar

    private void opcionGuardar(java.awt.event.ActionEvent evt)//GEN-FIRST:event_opcionGuardar
    {//GEN-HEADEREND:event_opcionGuardar
        ((ContactoTableModel)tablaDatos.getModel()).guardarAgenda();
    }//GEN-LAST:event_opcionGuardar

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {

            public void run()
            {
                new AgendaUI().setVisible(true);
            }
        });
    }

    public AbstractTableModel setTableModelAgenda()
    {
        ContactoTableModel modelo = new ContactoTableModel();
        return modelo;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelFicha;
    private javax.swing.JPopupMenu PopUpTabla;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JMenuItem opcionBorrarContacto;
    private javax.swing.JMenuItem opcionCargar;
    private javax.swing.JMenuItem opcionGuardar;
    private javax.swing.JMenuItem opcionNuevoContacto;
    private javax.swing.JTable tablaDatos;
    private javax.swing.JTextField textoDireccion;
    private javax.swing.JTextField textoEmail;
    private javax.swing.JTextField textoMovil;
    private javax.swing.JTextField textoNombre;
    private javax.swing.JTextField textoPrimerApellido;
    private javax.swing.JTextField textoSegundoApellido;
    private javax.swing.JTextField textoTelefono;
    // End of variables declaration//GEN-END:variables
}
